<?php


namespace App\Http\Controllers;


use App\Helpers\Helpers;
use App\Model\Cart;
use App\Model\Order;
use App\Model\OrderGoods;
use App\Model\Setting;
use Carbon\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class OrderController extends Controller
{

    /**
     * 从购物车创建订单
     * @author thanatos thanatos915@163.com
     */
    public function create()
    {
        $data = request()->all();

        // 验证购买人信息
        $validator = Validator::make($data, [
            'fullname' => 'required',
            'addressLine1' => 'required',
            'addressLine2' => '',
            'zipCode' => 'required|string',
            'city' => 'required|string',
            'country' => 'required|string',
            'email' => 'required|email',
        ]);

        if ($validator->fails()) {
            $error = $validator->errors();
            return response()->json(array_merge($error->toArray(), ['status' => 'error']));
        }

        $order = new Order();
        $order->generateOrderSn();
        $order->fill([
            'buy_name' => $data['fullname'],
            'address' => $data['addressLine1'],
            'zip_code' => $data['zipCode'],
            'country' => $data['country'],
            'city' => $data['city'],
            'email' => $data['email']
        ]);

        DB::transaction(function() use ($order) {
            $order->save();

            /** @var Cart[]|Collection $carts */
            $carts = Cart::where('user_id', Helpers::getUserId())->get();

            $total = 0;

            $orderGoods = [];
            foreach ($carts as $cart) {
                $price = $cart->goods->goods_price * $cart->number;
                array_push($orderGoods, [
                    'order_id' => $order->id,
                    'goods_id' => $cart->goods->id,
                    'number' => $cart->number,
                    'total_price' => $price,
                    'created_at' => Carbon::now(),
                    'updated_at' => Carbon::now(),
                ]);
                $total += $price;
            }
            OrderGoods::insert($orderGoods);
            $order->shopping_price = Setting::getShoppingPrice();
            $order->total_price = $total + $order->shopping_price;
            $order->save();
        });

        return response()->json($order);
    }

}
